//
//  CameraViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/9/10.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import AVFoundation

class CameraViewController: BaseViewController {
    
    var device:AVCaptureDevice!   //获取设备:如摄像头
    var input:AVCaptureDeviceInput!   //输入流
    var photoOutput:AVCaptureStillImageOutput! //输出流
    var  output:AVCaptureMetadataOutput! //当启动摄像头开始捕获输入
    var  session:AVCaptureSession!//会话,协调着intput到output的数据传输,input和output的桥梁
    var  previewLayer:AVCaptureVideoPreviewLayer! //图像预览层，实时显示捕获的图像
    
    var imageView: UIImageView?   //拍照后的成像
    var image: UIImage?   //拍照后的成像
    
    var imageUrl = ""
    
    var bottomViwe:UIView!
    var confirmView:UIView!
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        
        view.backClosure = { [weak self] in
            self?.cameraSet()
        }
        
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        guard canUserCamear() else {
            return
        }
        self.customCamera()
        self.customUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - 检查相机权限
    func canUserCamear() -> Bool {
        let authStatus: AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if authStatus == .denied {
            self.alertView.show(withTitle: "请在设备的\"设置-隐私-相机\"中允许访问相机~")
            return false
        }
        else {
            return true
        }
    }
    
    func cameraSet(){
        let url = URL.init(string: "App-Prefs:root=Privacy&path=CAMERA")
        let url1 = URL.init(string: UIApplicationOpenSettingsURLString)
        if #available(iOS 11, *) {
            if UIApplication.shared.canOpenURL(url1!) {
                UIApplication.shared.openURL(url1!)
            }
        }else{
            if UIApplication.shared.canOpenURL(url!) {
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url!, options:[:], completionHandler: nil)
                }else{
                    UIApplication.shared.openURL(url!)
                }
            }
        }
    }
    
    //MARK: 初始化自定义相机
    func customCamera(){
        
            let devices = AVCaptureDevice.devices(for: AVMediaType.video)  //初始化摄像头设备
            guard let device = devices.filter({ return $0.position == .back }).first else{ return}
            self.device = device
            //输入流初始化
            self.input = try? AVCaptureDeviceInput(device: device)
            //照片输出流初始化
            self.photoOutput = AVCaptureStillImageOutput.init()
             //输出流初始化
            self.output = AVCaptureMetadataOutput.init()
             //生成会话
            self.session = AVCaptureSession.init()
            if(self.session.canSetSessionPreset(AVCaptureSession.Preset(rawValue: "AVCaptureSessionPreset1280x720"))){
                self.session.sessionPreset = AVCaptureSession.Preset(rawValue: "AVCaptureSessionPreset1280x720")
            }
        
            if(self.session.canAddInput(self.input)){
                  self.session.addInput(self.input)
            }
        
            if(self.session.canAddOutput(self.photoOutput)){
                  self.session.addOutput(self.photoOutput)
            }
             //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
             self.previewLayer = AVCaptureVideoPreviewLayer.init(session: self.session)
             self.previewLayer.frame  = CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight)
            self.previewLayer.videoGravity = AVLayerVideoGravity(rawValue: "AVLayerVideoGravityResizeAspectFill")
             self.view.layer.addSublayer(self.previewLayer)
             //启动
             self.session.startRunning()
             if ((try? device.lockForConfiguration()) != nil) {
               if device.isFlashModeSupported(.auto) {
                       device.flashMode = .auto
                   }
               //自动白平衡
               if device.isWhiteBalanceModeSupported(.autoWhiteBalance) {
                       device.whiteBalanceMode = .autoWhiteBalance
                   }
               device.unlockForConfiguration()
           }
    
            //闪光灯
            do{ try device.lockForConfiguration() }catch{ }
            if device.hasFlash == false { return }
            device.flashMode = AVCaptureDevice.FlashMode.auto
            device.unlockForConfiguration()
        
    }
    
    func customUI(){
        
        let height:CGFloat = 80 + (Utils.isIphoneX() ? 34 : 0)
        let bgImageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight - 80 - (Utils.isIphoneX() ? 34 : 0)))
        bgImageView.image = UIImage.init(named: "saomiao_bg1")
        self.view.addSubview(bgImageView)
        
        bottomViwe = UIView.init(frame: CGRect.init(x: 0, y: UIScreen.ScreenHeight - 80 - (Utils.isIphoneX() ? 34 : 0), width: UIScreen.ScreenWidth, height: height))
        bottomViwe.backgroundColor = UIColor.init(hexColor: "#000000", alpha: 0.8)
        self.view.addSubview(bottomViwe)
        
        let button = UIButton.init(type: .custom)
        button.isUserInteractionEnabled = false
        button.frame = CGRect.init(x: UIScreen.ScreenWidth / 2 - 30, y: height/2 - 30 - (Utils.isIphoneX() ? 8 : 0), width: 60, height: 60)
        button.setImage(UIImage.init(named: "saomiao_queding_1"), for: .normal)
        bottomViwe.addSubview(button)
        
        let photoButton = UIButton.init(type: .custom)
        photoButton.frame = CGRect.init(x: UIScreen.ScreenWidth / 2 - 45/2, y: height/2 - 45/2 - (Utils.isIphoneX() ? 8 : 0), width: 45, height: 45)
        photoButton.addTarget(self, action: #selector(shutterCamera), for: .touchUpInside)
        photoButton.setImage(UIImage.init(named: "saomiao_queding_2_1"), for: .normal)
        bottomViwe.addSubview(photoButton)
        
        let backBtn = UIButton.init(type: .custom)
        backBtn.frame = CGRect.init(x: 12, y: (height - 25)/2, width: 15, height: 25)
        backBtn.setImage(UIImage.init(named: "saomiao_fanhui"), for: .normal)
        backBtn.addTarget(self, action: #selector(backBarButtonMethon), for: .touchUpInside)
        backBtn.centerY = photoButton.centerY
        bottomViwe.addSubview(backBtn)
        
        self.confirmView = UIView.init(frame: bottomViwe.frame)
        self.confirmView.backgroundColor = UIColor.clear
        self.confirmView.isHidden = true
        self.view.addSubview(self.confirmView)
        
        let cancelBtn = UIButton.init(type: .custom)
        cancelBtn.frame = CGRect.init(x: UIScreen.ScreenWidth/4 - 55/2, y: height/2 - 55/2 - (Utils.isIphoneX() ? 8 : 0), width: 55, height: 55)
        cancelBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        cancelBtn.setImage(UIImage.init(named: "sxd_tc"), for: .normal)
        cancelBtn.tag = 2000
        self.confirmView.addSubview(cancelBtn)
        
        let confirmBtn = UIButton.init(type: .custom)
        confirmBtn.frame = CGRect.init(x: UIScreen.ScreenWidth/4*3 - 55/2, y: cancelBtn.top, width: 55, height: 55)
        confirmBtn.setImage(UIImage.init(named: "sxd_qd"), for: .normal)
        confirmBtn.tag = 2001
        confirmBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        self.confirmView.addSubview(confirmBtn)
    }
    
    @objc func btnClick(sender:UIButton){
        if sender.tag == 2000 {
            self.confirmView.isHidden = true
            self.bottomViwe.isHidden = false
            self.imageView?.removeFromSuperview()
            self.image = nil
            self.session.startRunning()
        }else{
            self.uploadImage()
        }
    }
    
    func uploadImage(){
        PKhud.show()
        HttpRequest.uploadImage(image: self.image!) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                self.imageUrl = result["data"] as! String
                self.sheetupload()
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func sheetupload(){
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.userSheetAdd.rawValue, parameters: ["img":self.imageUrl]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: "手写单上传成功~")
                Utils.DispatchAfter(after: 2, handler: {
                   self.backBarButtonMethon()
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    
    
    //MARK:拍照按钮点击事件
    @objc func shutterCamera(){
        let videoConnection: AVCaptureConnection? = photoOutput.connection(with: .video)
        if videoConnection == nil {
            return
        }
        photoOutput.captureStillImageAsynchronously(from: videoConnection ?? AVCaptureConnection(), completionHandler: {(_ imageDataSampleBuffer: CMSampleBuffer?, _ error: Error?) -> Void in
                 if imageDataSampleBuffer == nil {
                      return
                   }
            let imageData: Data? = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer!)   //照片数据流
            self.image = UIImage(data: imageData!)
            self.session.stopRunning()
            self.imageView = UIImageView(frame: self.previewLayer.frame)
            self.imageView?.contentMode = UIViewContentMode.scaleAspectFill
            self.view.insertSubview(self.imageView!, belowSubview: self.bottomViwe!)
            self.imageView?.layer.masksToBounds = true
            self.imageView?.image = self.image
            print("image size = \(NSStringFromCGSize((self.image?.size)!))")
            self.confirmView.isHidden = false
            self.bottomViwe.isHidden = true
            
            })
        }

}
